<?php

namespace app\services\office;

use app\dao\office\OfficeChapterDao;
use app\exceptions\AdminException;
use app\services\BaseService;

class OfficeChapterService extends BaseService
{
    public function __construct(OfficeChapterDao $dao)
    {
        $this->dao = $dao;
    }

    public function getList(array $where)
    {
        return $this->dao->getList($where);
    }

    public function delete(array $where)
    {
        return $this->dao->deleteDao($where);
    }

    public function createOrUpdate(array $where)
    {
        if ($where['id']) return $this->dao->updateDao($where);
        return $this->dao->create($where);
    }

    public function getPidList(array $where)
    {
        return $this->dao->getPidList($where);
    }

    public function index(array $where)
    {
        return $this->dao->index($where);
    }

    //-----------------------------------------------api--------------------------------------------------------------

    /*
     * 获取章节目录
     */
    public function getChapter(array $where)
    {
        $data = $this->dao->getChapter($where);
        $record = $this->dao->getVideoRecord($where);
        for ($i = 0; $i < count($data); $i++) {
            $data[$i]['VideoRecord'] = null;
            for ($m = 0; $m < count($record); $m++) {
                if ($data[$i]['id'] == $record[$m]['chapter_id']) {
                    $data[$i]['VideoRecord'] = $record[$m];
                }
            }
        }
        return $this->create_tree_list(0, $data, 0);

    }

    /**
     * 递归实现无限极分类
     * @param $pid 父ID
     * @param $arr 递归数据
     * @param $level 分类级别
     * @return $list 分好类的数组 直接遍历即可 $level可以用来遍历缩进
     */
    public function create_tree_list($pid, $arr, $level, &$tree = [])
    {
        foreach ($arr as $key => $vo) {
            if ($vo['pid'] == $pid) {
                $vo['level'] = $level;
                $c = $this->create_tree_list($vo['id'], $arr, $level + 1);
                if ($c) {
                    $vo['children'] = $c;
                }
                $tree[] = $vo;

            }
        }
        return $tree;
    }
}